#!/bin/bash
# 设备管理系统环境管理脚本
# 提供快速切换和管理不同环境的功能

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_header() {
    echo -e "${PURPLE}🔧 设备管理系统环境管理工具${NC}"
    echo -e "${PURPLE}================================${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

show_help() {
    echo ""
    print_header
    echo ""
    echo -e "${CYAN}📖 环境管理工具使用说明${NC}"
    echo -e "${CYAN}========================${NC}"
    echo ""
    echo "基本命令:"
    echo "  info                           显示当前配置信息"
    echo "  switch <env>                   切换到指定环境"
    echo "  start [env] [options]          启动服务器"
    echo "  test                           运行测试（自动使用testing环境）"
    echo "  validate [env]                 验证配置"
    echo "  diff <env1> <env2>             比较两个环境的配置"
    echo "  create-sample <env>            创建示例配置文件"
    echo "  help                           显示此帮助信息"
    echo ""
    echo "可用环境:"
    echo "  development  - 开发环境（默认）"
    echo "  testing      - 测试环境"
    echo "  staging      - 预发布环境"
    echo "  production   - 生产环境"
    echo ""
    echo "启动选项:"
    echo "  --reload                       启用热重载（仅开发环境）"
    echo "  --host <address>               指定服务器地址"
    echo "  --port <port>                  指定端口"
    echo "  --log-level <level>            指定日志级别"
    echo ""
    echo "使用示例:"
    echo "  ./env_manager.sh info                          # 显示配置信息"
    echo "  ./env_manager.sh switch development            # 切换到开发环境"
    echo "  ./env_manager.sh start development --reload    # 启动开发服务器并热重载"
    echo "  ./env_manager.sh start production              # 启动生产服务器"
    echo "  ./env_manager.sh validate staging              # 验证预发布环境配置"
    echo "  ./env_manager.sh diff development production   # 比较开发和生产环境配置"
    echo ""
}

show_info() {
    print_info "显示当前配置信息..."
    python -m app.core.config_manager info
}

switch_env() {
    if [ -z "$1" ]; then
        print_error "请指定环境名称"
        echo "用法: ./env_manager.sh switch <environment>"
        echo "可用环境: development, testing, staging, production"
        return 1
    fi
    
    print_info "切换到 $1 环境..."
    export ENVIRONMENT=$1
    python -m app.core.config_manager switch $1
}

start_server() {
    local target_env=${1:-development}
    shift
    
    print_info "启动服务器 - $target_env 环境..."
    export ENVIRONMENT=$target_env
    python start_server.py --env $target_env "$@"
}

run_tests() {
    print_info "运行测试..."
    export ENVIRONMENT=testing
    python -m pytest tests/ -v
}

validate_config() {
    if [ -z "$1" ]; then
        print_info "验证当前环境配置..."
        python -m app.core.config_manager validate
    else
        print_info "验证 $1 环境配置..."
        python -m app.core.config_manager validate $1
    fi
}

compare_config() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        print_error "请指定两个环境名称进行比较"
        echo "用法: ./env_manager.sh diff <env1> <env2>"
        return 1
    fi
    
    print_info "比较 $1 和 $2 环境配置..."
    python -m app.core.config_manager diff $1 $2
}

create_sample() {
    if [ -z "$1" ]; then
        print_error "请指定环境名称"
        echo "用法: ./env_manager.sh create-sample <environment>"
        return 1
    fi
    
    print_info "创建 $1 环境示例配置文件..."
    python -m app.core.config_manager create-sample $1
}

# 主程序
main() {
    echo ""
    print_header
    
    case "${1:-help}" in
        "info")
            show_info
            ;;
        "switch")
            switch_env "$2"
            ;;
        "start")
            shift
            start_server "$@"
            ;;
        "test")
            run_tests
            ;;
        "validate")
            validate_config "$2"
            ;;
        "diff")
            compare_config "$2" "$3"
            ;;
        "create-sample")
            create_sample "$2"
            ;;
        "help"|"--help"|"-h")
            show_help
            ;;
        *)
            print_error "未知命令: $1"
            echo "使用 './env_manager.sh help' 查看帮助信息"
            exit 1
            ;;
    esac
    
    echo ""
}

# 检查Python环境
if ! command -v python &> /dev/null; then
    print_error "未找到 Python 环境，请确保已安装 Python"
    exit 1
fi

# 检查是否在正确的目录
if [ ! -f "start_server.py" ]; then
    print_error "请在项目根目录下运行此脚本"
    exit 1
fi

# 执行主程序
main "$@"